package com.douqu.game.activity.entity;

import com.alibaba.fastjson.JSONObject;
import com.bean.core.buffer.ByteBuffer;
import com.douqu.game.activity.GameServer;
import com.douqu.game.activity.database.model.ActivityCampModel;
import com.douqu.game.activity.manager.ActivityCampManager;
import com.douqu.game.activity.server.netty.NettyTCPClient;
import com.douqu.game.core.e.E_ActivityCampStatus;
import com.douqu.game.core.e.E_ApplyCampActivityType;
import com.douqu.game.core.e.E_MatchType;
import com.douqu.game.core.entity.activity.MatchBaseInfo;
import com.douqu.game.core.factory.CodeFactory;
import com.douqu.game.core.factory.ConstantFactory;
import com.douqu.game.core.i.IMainServer;
import com.douqu.game.core.util.LogUtils;
import com.douqu.game.core.util.SendUtils;
import io.netty.channel.Channel;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

/**
 * @Author: Bean
 * @Description:
 * @Date: 2018-03-08 15:39
 */
public class MainServerInfo {

    private int id;

    private String host;

    private int port;

    /**
     * 连接主服务器的
     */
    private NettyTCPClient tcpClient;

    /**
     * RMI方式连接主服务器
     */
    private IMainServer rmiServer;

    private Channel channel;

    public MainServerInfo(int id, String host, int port)
    {
        this.id = id;
        this.host = host;
        this.port = port;
    }


    public void startTCP()
    {
        if(tcpClient == null)
        {
            tcpClient = new NettyTCPClient();
            tcpClient.start(this);
        }
    }

    public void startRMI(String url)
    {
        try {
            //在RMI服务注册表中查找名称为X的对象，并调用其上的方法

            LogUtils.info(this + " 连接RMI:" + url);

            rmiServer = (IMainServer) Naming.lookup(url);

            LogUtils.info(this + " RMI 链接成功: " + url);

            GameServer.getInstance().addMainServerInfo(this);

//            sendCampActivityTime();

        } catch (NotBoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public boolean isConnectSuccess()
    {
        return tcpClient != null && rmiServer != null && channel != null;
    }

    public void stop()
    {
        LogUtils.warn("Server -> " + host + ":" + port + " Close......");
        if(tcpClient != null)
        {
            tcpClient.stop();
        }

        GameServer.getInstance().removeMainServerInfo(id, true);

        LogUtils.warn("重新链接一次 -> ");
        GameServer.getInstance().restartMainServer(id, host, port);
    }

    public void sendPing()
    {
        SendUtils.sendMsg(channel, CodeFactory.SERVER_PING);
    }

    /**
     * 回复报名成功
     * @param playerIndex
     */
    public void sendApplySuccess(String playerIndex, E_ApplyCampActivityType type)
    {
        ByteBuffer buffer = new ByteBuffer();
        buffer.writeUTF(playerIndex);
        buffer.writeUTF(type.name());

        SendUtils.sendMsg(channel, CodeFactory.ACTIVITY_CAMP_APPLY_SUCCESS, buffer.getBytes());
    }

    /**
     * 发送给玩家匹配成功的消息
     */
    public void sendMatchSuccess(String teamIndex, String playerIndex, E_MatchType matchType, MatchBaseInfo target)
    {
        ByteBuffer buffer = new ByteBuffer();

        JSONObject out = new JSONObject();
        out.put(CodeFactory.KEY_PLAYER_INDEX, playerIndex);
        out.put(CodeFactory.KEY_TEAM_INDEX, teamIndex);
        out.put("matchType", matchType);
        out.put("target", target);

        buffer.writeUTF(out.toJSONString());

        SendUtils.sendMsg(channel, CodeFactory.ACTIVITY_CAMP_MATCH_SUCCESS, buffer.getBytes());
    }

    public void sendStartBattle(String battleId, int battleType, int battleDetailType, String playerIndex, MatchBaseInfo target, String battleServerHost, int battleServerPort)
    {
        ByteBuffer buffer = new ByteBuffer();

        JSONObject out = new JSONObject();
        out.put(CodeFactory.KEY_BATTLE_ID, battleId);
//        out.put(CodeFactory.KEY_BATTLE_TYPE, battleType);
        out.put(CodeFactory.KEY_BATTLE_DETAIL_TYPE, battleDetailType);
        out.put(CodeFactory.KEY_PLAYER_INDEX, playerIndex);
        out.put(CodeFactory.KEY_BATTLE_SERVER_HOST, battleServerHost);
        out.put(CodeFactory.KEY_BATTLE_SERVER_PORT, battleServerPort);
        out.put(CodeFactory.KEY_TARGET, target);

        buffer.writeUTF(out.toJSONString());

        SendUtils.sendMsg(channel, CodeFactory.ACTIVITY_CAMP_START_BATTLE, buffer.getBytes());
    }

    public void sendActivityStatus(boolean running, boolean sendFirstCampPlayer)
    {
        JSONObject jsonObject = new JSONObject();
        ActivityCampManager activityCampManager = GameServer.getInstance().getActivityCampManager();
        jsonObject.put(CodeFactory.KEY_INDEX, activityCampManager.getIndex());
        jsonObject.put(CodeFactory.KEY_STATUS, activityCampManager.getStatus());
        jsonObject.put(CodeFactory.KEY_RUNNING, running);//主要用来判断是否是活动运行时间中开始的
        if(activityCampManager.getStatus() == E_ActivityCampStatus.RUN_ING)
        {
            jsonObject.put(ConstantFactory.RANK_PLAYER_LIST, activityCampManager.getRankPlayerList());
            jsonObject.put(ConstantFactory.RANK_CAMP_LIST, activityCampManager.getRankCampList());
        }

        if(sendFirstCampPlayer)
        {
            jsonObject.put(ConstantFactory.FIRST_CAMP_PLAYER_LIST, activityCampManager.getFirstCampPlayerList(id));
        }

        ByteBuffer buffer = new ByteBuffer();
        buffer.writeUTF(jsonObject.toJSONString());

        SendUtils.sendMsg(channel, CodeFactory.ACTIVITY_CAMP_STATUS, buffer.getBytes());
    }

    public void sendRankInfo(JSONObject jsonObject)
    {
        ByteBuffer buffer = new ByteBuffer();
        buffer.writeUTF(jsonObject.toJSONString());

        SendUtils.sendMsg(channel, CodeFactory.ACTIVITY_CAMP_RANK_INFO, buffer.getBytes());
    }

    /**
     * 通知阵营活动的时间
     */
    public void sendCampActivityTime()
    {
        JSONObject jsonObject = new JSONObject();
        ActivityCampModel activityCampModel = GameServer.getInstance().getActivityCampManager().getActivityCampModel();
        if(activityCampModel != null)
        {
            jsonObject.put(CodeFactory.KEY_START_TIME, activityCampModel.getStartTime().toString());
            jsonObject.put(CodeFactory.KEY_TOTAL_TIME, activityCampModel.getTotalTime());
            jsonObject.put(CodeFactory.KEY_INTERVAL_TIME, activityCampModel.getIntervalTime());

            ByteBuffer buffer = new ByteBuffer();
            buffer.writeUTF(jsonObject.toJSONString());

            SendUtils.sendMsg(channel, CodeFactory.ACTIVITY_CAMP_TIME, buffer.getBytes());
        }
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public NettyTCPClient getTcpClient() {
        return tcpClient;
    }

    public void setTcpClient(NettyTCPClient tcpClient) {
        this.tcpClient = tcpClient;
    }

    public IMainServer getRmiServer() {
        return rmiServer;
    }

    public void setRmiServer(IMainServer rmiServer) {
        this.rmiServer = rmiServer;
    }

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }




    @Override
    public String toString() {
        return "{" +
                "id=" + id +
                ", host='" + host + '\'' +
                ", port=" + port +
                '}';
    }
}
